package org.jeecg.modules.dzqzsqb.controller;

import java.awt.*;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.hebtx.exception.PDFServerSignException;
import com.hebtx.seal.sign.RemoteSign;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.dzqzsqb.entity.Dzqzsqb;
import org.jeecg.modules.dzqzsqb.service.IDzqzsqbService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 电子签章申请
 * @Author: jeecg-boot
 * @Date:   2021-12-02
 * @Version: V1.0
 */
@Api(tags="电子签章申请")
@RestController
@RequestMapping("/dzqzsqb/dzqzsqb")
@Slf4j
public class DzqzsqbController extends JeecgController<Dzqzsqb, IDzqzsqbService> {
	@Autowired
	private IDzqzsqbService dzqzsqbService;

	/**
	 * 分页列表查询
	 *
	 * @param dzqzsqb
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "电子签章申请-分页列表查询")
	@ApiOperation(value="电子签章申请-分页列表查询", notes="电子签章申请-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Dzqzsqb dzqzsqb,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Dzqzsqb> queryWrapper = QueryGenerator.initQueryWrapper(dzqzsqb, req.getParameterMap());
		Page<Dzqzsqb> page = new Page<Dzqzsqb>(pageNo, pageSize);
		IPage<Dzqzsqb> pageList = dzqzsqbService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param dzqzsqb
	 * @return
	 */
	@AutoLog(value = "电子签章申请-添加")
	@ApiOperation(value="电子签章申请-添加", notes="电子签章申请-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody Dzqzsqb dzqzsqb) {
		dzqzsqbService.save(dzqzsqb);
		return Result.OK("添加成功！");
	}

	/*
	电子签章盖章
	 */
	 @RequestMapping(value = "/gz")
	 public Result<?> dzqzgz(@RequestBody Dzqzsqb dzqzsqb) throws IOException {

	 	//获取当前登录用户真实姓名填充
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 dzqzsqb.setCreateBy(sysUser.getRealname());


	 	//判断文件后缀名
if(!"pdf".equals(dzqzsqb.getPdfname().substring(dzqzsqb.getPdfname().length()-3))){
	return Result.error("请上传pdf格式文件！");
}
      String str = dzqzsqb.getPdfname().substring(0,dzqzsqb.getPdfname().indexOf("/"));
      String pdfoutnames = dzqzsqb.getPdfname().substring(str.length()+1,dzqzsqb.getPdfname().length());

		 System.out.println(pdfoutnames);
     dzqzsqb.setPdfoutname("seal-"+pdfoutnames);

     boolean status = dzqzsqb.getPdfname().contains(",");
     if(status){
		 System.out.println("不能上传多个文件！");
     	return Result.error("不能同时上传多个文件进行签章！");

	 }


		String zjtqz ="http://121.28.5.194:9000/TXSealService/";
		String zhqz="http://121.28.5.194:9002/TXSealService/";
		String yqz="http://27.128.162.94:8888/TXSealServiceZJPB/";
		String dz="D:/question_collection/opt/upFiles/";

		 dzqzsqbService.save(dzqzsqb);

		 System.out.println(dz+dzqzsqb.getPdfname());
		 dzqzsqb.setPdfname(dz+dzqzsqb.getPdfname());
		 dzqzsqb.setPdfoutname("D:/question_collection/opt/upFiles/temp/"+dzqzsqb.getPdfoutname());


		 if ("专家通".equals(dzqzsqb.getSealname())){
			 dzqzsqb.setSealname(zjtqz);
		 }
		 if("中惠签章".equals(dzqzsqb.getSealname())){
			 dzqzsqb.setSealname(zhqz);
		 }
		 if ("云签章".equals(dzqzsqb.getSealname())){
			 dzqzsqb.setSealname(yqz);
		 }


		 JSONObject json = new JSONObject();
		 try {

			 String sealname = dzqzsqb.getQzchoose();
			 String keyword = dzqzsqb.getKeyword();


			 String pdfname = dzqzsqb.getPdfname();
			 String outname = dzqzsqb.getPdfoutname();
			 InputStream in = new FileInputStream(pdfname);
			 StringBuffer buffer = new StringBuffer();
			 buffer.append("<?xml version='1.0' encoding='UTF-8'?>" +
					 "<SIGNACTIONS>" +
					 "<SIGNACTION>" +
					 "<SEALTYPE>0</SEALTYPE>" +
					 "<MULTISHOW>0</MULTISHOW>" +//软证书服务端签章4349902841254039818
					 "<SEALUNIQUE>" + sealname + "</SEALUNIQUE>" +
					 "<SEALCERTPASS>123456</SEALCERTPASS>" +//x服务端印章8112264111160839205
					 "<PAGE>0</PAGE>" +
					 "<LOCATIONTYPE>1</LOCATIONTYPE>" +
					 "<KEYWORD>" + keyword + "</KEYWORD>" +
					 "<KEYWORDOFFSET>20,-50</KEYWORDOFFSET>" +
					 "</SIGNACTION>" +
					 "</SIGNACTIONS>");
			 byte is[] = null;
			 try {
				 String url = dzqzsqb.getSealname();
				 is = RemoteSign.textSignAndSealOnServer(url, pdfname, in, buffer.toString());
			 } catch (PDFServerSignException e) {
				 System.out.println(URLDecoder.decode(e.getMessage(), "UTF-8"));
			 }
			 FileOutputStream fos = new FileOutputStream(outname);
			 fos.write(is);
			 fos.close();
			 in.close();
			 json.put("success", true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 json.put("success", false);

		 }

		 return Result.OK("盖章成功！");
		 //打开文件夹
	 }


	 public static void main(String[] args) throws IOException {

		 JSONObject json = new JSONObject();
		 try {
         /*\
          * 赵健勇的签章3750217506663905046
刘春溥的签章5658324675072433949
汤晓良的签章5428830784090902187
徐银宝的签章3404269228960398456
封美丽的签章8088867661143769765
user_name  seal_cn
张瑞稳718415  张瑞稳的签章5834382552736754779
楚玲锋872910  楚玲锋的签章1071965657248433521
贾杰553912   贾杰的签章5094749898240950496
韩健斌747755  韩健斌的签章3544731116314825152
赵生珍651940  赵生珍的签章3250682354163480943
          */
			 String sealname = "河北中惠博裕科技有限公司4655113562013031675";
			 String keyword = "盖章";
			 String pdfname = "g:/附件2：评标时间记取方式描述(2).pdf";
			 String outname = "g:/附件2：签章完成评标时间记取方式描述(2).pdf";
			 InputStream in = new FileInputStream(pdfname);
			 StringBuffer buffer = new StringBuffer();
			 buffer.append("<?xml version='1.0' encoding='UTF-8'?>" +
					 "<SIGNACTIONS>" +
					 "<SIGNACTION>" +
					 "<SEALTYPE>0</SEALTYPE>" +
					 "<MULTISHOW>0</MULTISHOW>" +//软证书服务端签章4349902841254039818
					 "<SEALUNIQUE>" + sealname + "</SEALUNIQUE>" +
					 "<SEALCERTPASS>123456</SEALCERTPASS>" +//x服务端印章8112264111160839205
					 "<PAGE>0</PAGE>" +
					 "<LOCATIONTYPE>1</LOCATIONTYPE>" +
					 "<KEYWORD>" + keyword + "</KEYWORD>" +
					 "<KEYWORDOFFSET>20,-50</KEYWORDOFFSET>" +
					 "</SIGNACTION>" +
					 "</SIGNACTIONS>");
			 byte is[] = null;
			 try {
				 String url = "http://192.168.1.232:9002/TXSealService/";
				 is = RemoteSign.textSignAndSealOnServer(url, pdfname, in, buffer.toString());
			 } catch (PDFServerSignException e) {
				 System.out.println(URLDecoder.decode(e.getMessage(), "UTF-8"));
			 }
			 FileOutputStream fos = new FileOutputStream(outname);
			 fos.write(is);
			 fos.close();
			 in.close();
			 json.put("success", true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 json.put("success", false);

		 }

	 }







	/**
	 *  编辑
	 *
	 * @param dzqzsqb
	 * @return
	 */
	@AutoLog(value = "电子签章申请-编辑")
	@ApiOperation(value="电子签章申请-编辑", notes="电子签章申请-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody Dzqzsqb dzqzsqb) {
		dzqzsqbService.updateById(dzqzsqb);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电子签章申请-通过id删除")
	@ApiOperation(value="电子签章申请-通过id删除", notes="电子签章申请-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		dzqzsqbService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "电子签章申请-批量删除")
	@ApiOperation(value="电子签章申请-批量删除", notes="电子签章申请-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.dzqzsqbService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电子签章申请-通过id查询")
	@ApiOperation(value="电子签章申请-通过id查询", notes="电子签章申请-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Dzqzsqb dzqzsqb = dzqzsqbService.getById(id);
		if(dzqzsqb==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(dzqzsqb);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param dzqzsqb
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Dzqzsqb dzqzsqb) {
        return super.exportXls(request, dzqzsqb, Dzqzsqb.class, "电子签章申请");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Dzqzsqb.class);
    }

}
